<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="96px">
      <el-form-item label="社团名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入社团名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属类型" prop="typeId">
        <el-select v-model="queryParams.typeId" placeholder="请选择所属类型" clearable>
          <el-option
            v-for="dict in dict.type.club_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属二级学院" prop="secondaryCollegeId">
        <el-select v-model="queryParams.secondaryCollegeId" placeholder="请选择所属二级学院" clearable>
          <el-option
            v-for="college in collegeList"
            :key="college.id"
            :label="college.name"
            :value="college.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['campus:club:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['campus:club:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['campus:club:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['campus:club:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-view"
          size="mini"
          @click="handleViewApplications"
        >查看申请</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="clubList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="社团名称" align="center" prop="name" />
      <el-table-column label="所属类型" align="center" prop="typeId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.club_type" :value="scope.row.typeId"/>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="directorId">
        <template slot-scope="scope">
          {{ getUserName(scope.row.directorId) }}
        </template>
      </el-table-column>
      <el-table-column label="社团人数" align="center" prop="memberCount" />
      <el-table-column label="所属二级学院" align="center" prop="secondaryCollegeId">
        <template slot-scope="scope">
          {{ getCollegeName(scope.row.secondaryCollegeId) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="关注量" align="center" prop="followCount" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleApply(scope.row)"
          >申请</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleFollow(scope.row)"
          >关注</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['campus:club:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['campus:club:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改社团管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="社团名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入社团名称" />
        </el-form-item>
        <el-form-item label="所属类型" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择所属类型">
            <el-option
              v-for="dict in dict.type.club_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人" prop="directorId">
          <el-select v-model="form.directorId" placeholder="请选择负责人" clearable>
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属二级学院" prop="secondaryCollegeId">
          <el-select v-model="form.secondaryCollegeId" placeholder="请选择所属二级学院" clearable>
            <el-option
              v-for="college in collegeList"
              :key="college.id"
              :label="college.name"
              :value="college.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 申请加入社团对话框 -->
    <el-dialog title="申请加入社团" :visible.sync="applyOpen" width="500px" append-to-body>
      <el-form ref="applyForm" :model="applyForm" :rules="applyRules" label-width="80px">
        <el-form-item label="社团名称">
          <el-input v-model="applyForm.clubName" disabled />
        </el-form-item>
        <el-form-item label="申请理由" prop="applyReason">
          <el-input 
            v-model="applyForm.applyReason" 
            type="textarea" 
            placeholder="请输入申请理由"
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApply">确 定</el-button>
        <el-button @click="cancelApply">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 社团申请列表对话框 -->
    <el-dialog title="社团申请列表" :visible.sync="applicationOpen" width="800px" append-to-body>
      <el-table v-loading="applicationLoading" :data="applicationList">
        <el-table-column label="社团名称" align="center" prop="clubName" />
        <el-table-column label="申请人" align="center" prop="applicantName" />
        <el-table-column label="理由" align="center" prop="applyReason" />
        <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status === 0" type="warning">申请中</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">同意</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="danger">拒绝</el-tag>
            <span v-else>{{ scope.row.status }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handleApproveApplication(scope.row)"
              v-if="scope.row.status === 0"
            >同意</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-close"
              @click="handleRejectApplication(scope.row)"
              v-if="scope.row.status === 0"
            >拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="applicationTotal>0"
        :total="applicationTotal"
        :page.sync="applicationQueryParams.pageNum"
        :limit.sync="applicationQueryParams.pageSize"
        @pagination="getApplicationList"
      />
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelApplication">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listClub, getClub, delClub, addClub, updateClub, followClub } from "@/api/campus/club"
import { applyToClub, listApplicationsForCurrentUser, approveApplication, rejectApplication } from "@/api/campus/application"
import { listUser } from "@/api/system/user"
import { listCollege } from "@/api/campus/college"

export default {
  name: "Club",
  dicts: ['club_type', 'application_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 社团管理表格数据
      clubList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示申请弹出层
      applyOpen: false,
      // 是否显示申请列表弹出层
      applicationOpen: false,
      // 申请列表加载
      applicationLoading: false,
      // 申请列表数据
      applicationList: [],
      // 申请列表总数
      applicationTotal: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        typeId: null,
        secondaryCollegeId: null,
      },
      // 申请列表查询参数
      applicationQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 申请表单参数
      applyForm: {
        clubId: null,
        clubName: "",
        applyReason: ""
      },
      // 用户列表
      userList: [],
      // 二级学院列表
      collegeList: [],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "社团名称不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "所属类型不能为空", trigger: "change" }
        ],
        directorId: [
          { required: true, message: "负责人不能为空", trigger: "change" }
        ],
        secondaryCollegeId: [
          { required: true, message: "所属二级学院不能为空", trigger: "change" }
        ],
      },
      // 申请表单校验
      applyRules: {
        applyReason: [
          { required: true, message: "申请理由不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getUserList()
    this.getCollegeList()
  },
  methods: {
    /** 查询社团管理列表 */
    getList() {
      this.loading = true
      listClub(this.queryParams).then(response => {
        this.clubList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 获取用户列表
    getUserList() {
      listUser({ pageSize: 10000 }).then(response => {
        this.userList = response.rows
      })
    },
    // 获取二级学院列表
    getCollegeList() {
      listCollege({ pageSize: 10000 }).then(response => {
        this.collegeList = response.rows
      })
    },
    // 根据ID获取用户名称
    getUserName(userId) {
      const user = this.userList.find(item => item.userId === userId)
      return user ? user.userName : userId
    },
    // 根据ID获取二级学院名称
    getCollegeName(collegeId) {
      const college = this.collegeList.find(item => item.id === collegeId)
      return college ? college.name : collegeId
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        typeId: null,
        directorId: null,
        memberCount: null,
        secondaryCollegeId: null,
        followCount: null,
        createTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加社团管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getClub(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改社团管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClub(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addClub(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除社团管理编号为"' + ids + '"的数据项？').then(function() {
        return delClub(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 关注按钮操作 */
    handleFollow(row) {
      followClub(row.id).then(response => {
        this.$modal.msgSuccess("关注成功")
        // 更新关注量显示
        this.getList()
      }).catch(() => {})
    },
    /** 申请按钮操作 */
    handleApply(row) {
      this.applyForm = {
        clubId: row.id,
        clubName: row.name,
        applyReason: ""
      }
      this.applyOpen = true
    },
    // 取消申请
    cancelApply() {
      this.applyOpen = false
      this.resetForm("applyForm")
    },
    // 提交申请
    submitApply() {
      this.$refs["applyForm"].validate(valid => {
        if (valid) {
          const applicationData = {
            clubId: this.applyForm.clubId,
            applyReason: this.applyForm.applyReason
          }
          applyToClub(applicationData).then(response => {
            this.$modal.msgSuccess("申请成功")
            this.applyOpen = false
          }).catch(() => {})
        }
      })
    },
    /** 查看申请按钮操作 */
    handleViewApplications() {
      this.applicationOpen = true
      this.$nextTick(() => {
        this.getApplicationList()
      })
    },
    // 获取申请列表
    getApplicationList() {
      this.applicationLoading = true
      // 获取当前登录用户的ID
      const userId = this.$store.getters.id
      console.log("获取申请列表，用户ID:", userId)
      if (!userId) {
        console.error("无法获取当前用户ID")
        this.applicationLoading = false
        return
      }
      
      listApplicationsForCurrentUser(userId).then(response => {
        console.log("接口调用成功，返回数据:", response)
        // 后端返回的是List<List<ClubApplication>>结构，需要展开处理
        let allApplications = []
        if (response.rows && Array.isArray(response.rows)) {
          response.rows.forEach(clubApplications => {
            if (Array.isArray(clubApplications)) {
              allApplications = allApplications.concat(clubApplications)
            }
          })
        }
        this.applicationList = allApplications
        this.applicationTotal = allApplications.length
        this.applicationLoading = false
      }).catch(error => {
        console.error("接口调用失败:", error)
        this.applicationLoading = false
      })
    },
    // 取消查看申请
    cancelApplication() {
      this.applicationOpen = false
      this.applicationList = []
      this.applicationTotal = 0
      this.applicationQueryParams = {
        pageNum: 1,
        pageSize: 10
      }
    },
    // 同意申请
    handleApproveApplication(row) {
      this.$modal.confirm('是否确认同意"' + row.applicantName + '"的申请？').then(() => {
        return approveApplication(row.id)
      }).then(() => {
        this.$modal.msgSuccess("已同意申请")
        this.getApplicationList()
      }).catch(() => {})
    },
    // 拒绝申请
    handleRejectApplication(row) {
      this.$modal.confirm('是否确认拒绝"' + row.applicantName + '"的申请？').then(() => {
        return rejectApplication(row.id)
      }).then(() => {
        this.$modal.msgSuccess("已拒绝申请")
        this.getApplicationList()
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('campus/club/export', {
        ...this.queryParams
      }, `club_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>